package com.linwen.javase.thread.threadlocal;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalTest {

    private static String context;
     private static ThreadLocal<String> localContext = new ThreadLocal<>();

    @Test
    public void test(){
        ExecutorService threadPool = Executors.newFixedThreadPool(25);
        for (int i = 0; i < 50; i++) {
            int finalI = i;
            threadPool.execute(()->MyThreadLocal.doSomeThing(finalI));
        }
        try{
            Thread.sleep(50);
            } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void test1(){

        for (int i = 0; i < 300; i++) {
            new Thread(() -> {
                ThreadLocalTest.context = Thread.currentThread().getName();
                System.out.println("===================================");
                System.out.println("当前线程"+Thread.currentThread().getName()+" 线程变量为 "+ThreadLocalTest.context);
            },""+i).start();
        }
    }

    @Test
    public void test2(){

        for (int i = 0; i < 300; i++) {
            new Thread(() -> {
                ThreadLocalTest.localContext.set(Thread.currentThread().getName());
                System.out.println("===================================");
                System.out.println("当前线程"+Thread.currentThread().getName()+" 线程变量为 "+ThreadLocalTest.localContext.get());
            },""+i).start();
        }
    }
}
